package com.example.config;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;

@MapperScan(basePackages = {"com.example.mapper.ds2"}, sqlSessionFactoryRef  = "SqlSessionFactory2", annotationClass = Mapper.class)
@Component
public class DS2DataSourceConfig {
    @ConfigurationProperties(prefix = "spring.datasource.ds2")
    
    @Bean("DataSource2")
    public DataSource mysqlDataSource2() {
        return DataSourceBuilder.create().build();
    }

    @Bean("SqlSessionFactory2")
    
    public SqlSessionFactory sqlSessionFactory2(@Qualifier("DataSource2") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/ds2/*Mapper.xml"));
        return sqlSessionFactoryBean.getObject();
    }

    @Bean("sqlSessionTemplate2")
    
    public SqlSessionTemplate sqlSessionTemplate2(@Qualifier("SqlSessionFactory2") SqlSessionFactory sqlSessionFactory) throws Exception {
        SqlSessionTemplate sqlSessionTemplate = new SqlSessionTemplate(sqlSessionFactory);
        return sqlSessionTemplate;
    }

    @Bean("transactionManager2")
    public DataSourceTransactionManager transactionManager2(@Qualifier("DataSource2") DataSource dataSource) {
        DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource);
        return transactionManager;

    }

}



